package com.wbs.shop.nuby.view.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wbs.shop.nuby.R;
import com.wbs.shop.nuby.api.ApiHelper;
import com.wbs.shop.nuby.api.RxHelper;
import com.wbs.shop.nuby.api.RxSubscribe;
import com.wbs.shop.nuby.bean.GoodsBean;
import com.wbs.shop.nuby.bean.GoodsShowBean;
import com.wbs.shop.nuby.bean.SpecBean;
import com.wbs.shop.nuby.commom.Key;
import com.wbs.shop.nuby.helper.CashierHelper;
import com.wbs.shop.nuby.helper.RefreshHelper;
import com.wbs.shop.nuby.utils.Utils;
import com.wbs.shop.nuby.view.activity.CashierActivity;
import com.wbs.shop.nuby.view.activity.CashierActivityPadActivity;
import com.wbs.shop.nuby.view.activity.CashierPayActivity;
import com.wbs.shop.nuby.view.adapter.CarAdapter;
import com.wbs.shop.nuby.view.adapter.GoodsAdapter;
import com.wbs.shop.nuby.view.base.BaseFragment;
import com.wbs.shop.nuby.view.dialog.AlertDialog;
import com.wbs.shop.nuby.view.dialog.GoodsSpecDialog;
import com.wbs.shop.nuby.view.listener.SimplTextWatcher;
import com.wbs.shop.nuby.widget.SearchEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.subjects.PublishSubject;
import me.jessyan.autosize.utils.AutoSizeUtils;

public class CashierFragment extends BaseFragment {
    private static final String IS_PAD = "IS_PAD";

    public static CashierFragment newInstance(boolean isPad) {
        CashierFragment cashierFragment = new CashierFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_PAD, isPad);
        cashierFragment.setArguments(bundle);
        return cashierFragment;
    }

    @BindView(R.id.et_search)
    SearchEditText etSearch;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.car_recyclerview)
    RecyclerView carRecView;
    @BindView(R.id.settlement)
    TextView tvSettlement;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.iv_car)
    ImageView ivCar;
    @BindView(R.id.tv_badge)
    TextView tvBadge;
    BottomSheetBehavior behavior;
    private GoodsAdapter mGoodsAdapter;
    private CarAdapter carAdapter;
    private RefreshHelper<List<GoodsBean>> mRefreshHelper;
    private boolean isPad = false;

    @Override
    protected int tellMeLayout() {
        return R.layout.fragment_cashier;
    }

    @Override
    public void init(View rootView, Bundle savedInstanceState) {
        if (hasExtras()) {
            isPad = getArguments().getBoolean(IS_PAD, false);
        }
        if (isPad) {// 平板修改为查看购物车
            tvSettlement.setText(R.string.button_view_shopping_cart);
        }
        etSearch.setHint(R.string.text_hint_input_goods_name);
        etSearch.addTextChangedListener(new SimplTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                mRefreshHelper.onRefresh();
            }
        });
        mGoodsAdapter = new GoodsAdapter(getContext());
        mGoodsAdapter.setOnClickAdapterListenter(this::onClick);
        mRefreshHelper = new RefreshHelper<List<GoodsBean>>(recyclerview, refreshLayout, mGoodsAdapter) {
            @Override
            public void loadData() {
                getGoodsList();
            }
        };
        int dp5 = AutoSizeUtils.dp2px(getContext(), 5);;
        recyclerview.setPadding(dp5, dp5, dp5, dp5);
        recyclerview.setLayoutManager(new GridLayoutManager(getContext(), isPad ? 4 : 2));
        mRefreshHelper.onRefresh();
        behavior = BottomSheetBehavior.from(findViewById(R.id.pop_layout));
        PublishSubject<Object> numberChangPublishSubject = PublishSubject.create();
        add(numberChangPublishSubject.subscribe(o -> changMoney()));
        carAdapter = new CarAdapter(getContext(), numberChangPublishSubject);
        carAdapter.setDatas(new ArrayList<>());
        carRecView.setLayoutManager(new LinearLayoutManager(getContext()));
        carRecView.setAdapter(carAdapter);
        ((DefaultItemAnimator) carRecView.getItemAnimator()).setSupportsChangeAnimations(false);
        changMoney();
    }

    private void onClick(View view, int position) {
        ApiHelper.getApiService().getGoodsDetail(mGoodsAdapter.getItem(position).getId())
                .compose(RxHelper.handleResult(this))
                .subscribe(new RxSubscribe<GoodsBean>(getContext()) {
                    @Override
                    protected void _onNext(GoodsBean goodsBean) {
                        List<SpecBean> specList = goodsBean.getSpecList();
                        if (specList.isEmpty()) {
                            addGoods(CashierHelper.goodsTOGoodsShow(goodsBean, 1));
                        } else {
                            new GoodsSpecDialog.Builder(getContext())
                                    .goodsBean(goodsBean)
                                    .specBeanList(specList)
                                    .onSelectGoodsSpecListener(goodsShowBean -> addGoods(goodsShowBean))
                                    .create()
                                    .show();
                        }
                    }
                });

    }

    private void getGoodsList() {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("name", etSearch.getText().toString());
        jsonParam.put("agent", 0);
        ApiHelper.getApiService().getGoodsList(jsonParam.toJSONString(), mRefreshHelper.getPageNo())
                .compose(RxHelper.handleResult(this))
                .subscribe(mRefreshHelper.getRxSubscribe());
    }

    @OnClick({R.id.blackview, R.id.clearCar, R.id.ll_car_main, R.id.settlement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clearCar:
                clearCar();
                break;
            case R.id.ll_car_main:
                showCart();
                break;
            case R.id.settlement:
                if (isPad) {
                    showCart();
                } else {
                    if (carAdapter.getItemCount() < 1) {
                        Utils.toastMessageLong("请先选择商品");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList(Key.GOODS_SHOW, (ArrayList<? extends Parcelable>) carAdapter.getDatas());
                    bundle.putString(Key.PAY_AMOUNT, carAdapter.getTotalAmount());
                    goActicityForResult(CashierPayActivity.class, Key.REQUEST_CODE, bundle);
                }
                break;
            case R.id.blackview:
                collapsed();
                break;
        }
    }

    private void showCart() {
        if (carAdapter.getItemCount() > 0) {
            if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            } else {
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        }
    }

    private void addGoods(GoodsShowBean goodsShowBean) {
        carAdapter.addGoods(goodsShowBean);
        changeGoods();
    }

    private void changeGoods() {
        if (isPad) {
            ((CashierActivityPadActivity) getActivity()).changeGoods(carAdapter.getDatas(), carAdapter.getTotalAmount());
        }
    }

    public void changeDiscount(double discount) {
        carAdapter.changeDiscount(discount);
    }

    private void clearCar() {
        new AlertDialog.Builder(getContext())
                .setMessage(R.string.dialog_message_clear_all)
                .setNegativeButton(R.string.button_cancel, null)
                .setPositiveButton(R.string.button_clear, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doClearCar();
                    }
                })
                .create()
                .show();
    }

    public void doClearCar() {
        carAdapter.getDatas().clear();
        carAdapter.notifyDataSetChanged();
        collapsed();
        changMoney();
    }

    private void changMoney() {
        int totalQuantity = carAdapter.getTotalQuantity();
        tvBadge.setVisibility(totalQuantity > 0 ? View.VISIBLE : View.GONE);
        tvBadge.setText(String.valueOf(totalQuantity));
        if (totalQuantity < 1)
            collapsed();
        totalMoney.setText(getString(R.string.text_total_money, carAdapter.getTotalAmount()));
        changeGoods();
    }

    private void collapsed() {
        if (behavior != null)
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Key.REQUEST_CODE && resultCode == Activity.RESULT_OK)
            doClearCar();
    }
}
